package com.sbx.advice;

import com.sbx.execption.MyException;
import com.sbx.utils.Result;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
@Slf4j
public class MyControllerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result bingError(MethodArgumentNotValidException e) {
        e.printStackTrace();
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return Result.fail(objectError.getDefaultMessage());
    }

    @ExceptionHandler(MyException.class)
    public Result myError(MyException e) {
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result myError(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.fail(StringUtils.isEmpty(e.getMessage())? "请求异常": e.getMessage());
    }
}






